package cn.bluech.lib.utils;

import android.app.Activity;
import android.graphics.Rect;
import android.view.View;

public class KeypadUtils {
    private static final String TAG = "KeypadUtils";
    // 虚拟键盘高度(三个虚拟按键)
    private static final int KEY_BAR_HEIGHT_THRESHOLD = 200;
    private final Activity activity;
    private final View rootView;

    private int keyBarHeight;
    private int keypadLastHeight;

    private Listener listener;

    public KeypadUtils(Activity activity){
        this.activity = activity;
        rootView = activity.getWindow().getDecorView().getRootView();
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            // 根布局的高度变化
            int height = getBottomOffset();

            /*if (Build.VERSION.SDK_INT >= 20) {
                // When SDK Level >= 20 (Android L), the softInputHeight will contain the height of softButtonsBar (if has)
                keypadHeight = keypadHeight - getSoftButtonsBarHeight();
            }*/
            if(height>KEY_BAR_HEIGHT_THRESHOLD){
                keypadLastHeight = height - keyBarHeight;
            }else{
                keyBarHeight = height;
            }
            if(null!=listener)
                listener.onKeypadChange(height>KEY_BAR_HEIGHT_THRESHOLD);
        });
    }

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    private int getBottomOffset() {
        Rect frameRect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frameRect);
        int screenHeight = activity.getWindow().getDecorView().getRootView().getHeight();

        return screenHeight - frameRect.bottom;
    }

    public int getKeypadHeight(int def) {
        if(keypadLastHeight>0)
            return keypadLastHeight;

        return def;
    }

    public boolean isShowing(){
        return getKeypadHeight(0)>KEY_BAR_HEIGHT_THRESHOLD;
    }

    public interface Listener{
        // adjustResize才有效
        void onKeypadChange(boolean isShow);
    }
}
